package com.example.blog.interceptor;

import com.example.blog.constant.Constants;
import com.example.blog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.aopalliance.intercept.Interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-01-08
 * Time: 12:28
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor{
    //请求前进行拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1:获取token
        //2：校验token，判断是否放行
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);//我们从前端请求中的Header中去获取token
        log.info("从Header中获取token：{}",token);
        Claims claims = JwtUtils.parseToken(token);
        if(claims == null){
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
